<template>
  <div class="v-editor-apply-to-elements g-pd-l-8 g-pd-r-4 g-jc-sb">
    <div>{{ allName }}</div>

    <div
      v-if="selected && !row.readonly && !isModelDisabled && !tableElementDisabled"
      class="img-btn g-m-l-4"
    >
      <img
        src="statics/icons/app/iconmore.png"
        class="g-pointer"
        @click="handleClick"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { PropertyRow } from "../../types";
import { Ref, inject, ref, watch } from "vue";
import { modelService } from "@/modules/model/service";
import { BusEvent, PropertyKey } from "@/constants/Enums";
import { ModelData } from "@/mdesign-lib/mdesign-app.umd.js";
import elementSelectModal from "@/modules/model/modals/changeRuleConfig/modals/elementSelect.vue";
import { locale } from "@/util/locale";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
  tableElementDisabled?: boolean;
}>();

const allName = ref("");
let selectedIdList: string[] = [];

let parentId = "";
let isNameUni = false;
let defaultName = "";
let prefixRule = "";
let separator = "";
let prefix = "";

watch(
  () => props.row.value,
  () => {
    selectedIdList = [];
    allName.value = "";

    if (props.row.value) {
      const models = props.row.value as ModelData[];

      models.forEach(item => {
        selectedIdList.push(item.id);
        allName.value = !allName.value
          ? locale.getTByKey(`modelConfig.${item.name}`, item.name)
          : `${allName.value}、${locale.getTByKey(`modelConfig.${item.name}`, item.name)}`;
      });
    }
  },
  {
    deep: true,
    immediate: true
  }
);

const handleClick = async () => {
  elementSelectModal
    .popup({
      projectId: app.activeProjectId,
      multiple: true,
      selectedNodeIds: selectedIdList,
      isRule: true
    })
    .then(async res => {
      if (res) {
        // 更新
        const list = await modelService.getModelProperties(app.activeProjectId, props.row.modelId);
        let ownerValue = list.find(item => item.key === PropertyKey.Element_owner)?.value as ModelData;
        parentId = ownerValue.id;

        list.forEach(item => {
          switch (item.key) {
            case PropertyKey.Customization_NamingRule_isNameUni:
              isNameUni = item.value as boolean;
              break;

            case PropertyKey.Customization_NamingRule_defaultName:
              defaultName = item.value as string;
              break;

            case PropertyKey.Customization_NamingRule_prefixRule:
              {
                let prefixRuleValue = item.value as ModelData;
                prefixRule = prefixRuleValue ? prefixRuleValue.id : "";
              }
              break;

            case PropertyKey.Customization_NamingRule_separator:
              separator = item.value as string;
              break;

            case PropertyKey.Customization_NamingRule_prefix:
              prefix = item.value as string;
              break;

            default:
              break;
          }
        });

        const updateRes = await modelService.batchUpdateNamingRule({
          projectId: app.activeProjectId,
          parentId,
          namingRules: [
            {
              dataType: "update",
              nameRuleId: props.row.modelId,
              applyToElements: res.map(item => item.instanceId) || [],
              isNameUni,
              defaultName,
              prefixRule,
              separator,
              prefix
            }
          ]
        });

        if (updateRes) {
          selectedIdList = res.map(item => item.instanceId) || [];
          allName.value = res.map(item => locale.getTByKey(`modelConfig.${item.name}`, item.name)).join("、");

          app.$bus.emit(BusEvent.REFRESH_PROPERTY, props.row.modelId);
        }
      }
    });
};
</script>

<style lang="scss" scoped>
.v-editor-apply-to-elements {
  height: 100%;
  overflow: hidden;
  & > div:first-child {
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .img-btn {
    flex-shrink: 0;
    display: flex;
    align-items: center;
  }
}
</style>
